package common;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * 处理来自client的请求.
 * 进行推模型.发送通知到注册了的client.
 * server动作处理线程.
 *
 * @author guanweichen
 * @version Jan 18, 2011
 */
public class ClientHandle extends Thread {

	/** 服务对象 */
	protected Server server;
	/** 客服端请求对象 */
	protected Socket client;
	
	public Server getServer() {
		return server;
	}
	public Socket getClient() {
		return client;
	}
	public void setServer(Server server) {
		this.server = server;
	}
	public void setClient(Socket client) {
		this.client = client;
	}
	/**
	 * send a command to client.
	 * 
	 * @param cmd
	 * @param socket
	 * @return
	 */
	protected synchronized Object sendCmd(Command cmd, Socket socket) {
		
		try {
			ObjectOutputStream cmdOut = new ObjectOutputStream(socket.getOutputStream());
			cmdOut.writeObject(cmd);
			cmdOut.flush();
			ObjectInputStream objectIn = new ObjectInputStream(socket.getInputStream());
			return objectIn.readObject();
		} catch (IOException e) {
			System.out.println("ERROR: can't connect client :[ ip: " + socket.getLocalAddress() + ", port: " + socket.getPort() + "]");
			System.out.println("Send command ERROR!");
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			System.out.println("ERROR: can't connect client :[ ip: " + socket.getLocalAddress() + ", port: " + socket.getPort() + "]");
			System.out.println("Send command ERROR!");
			e.printStackTrace();
		}
		return null;
	}
}
